# === 配置部分 ===
$ProjectPath = "D:\school_project\single-slope\RuoYi-Vue3"
$BuildDir = "dist"                   # 构建后要上传的整个 dist 文件夹
$ServerUser = "root"
$ServerIp = "39.107.238.187"
$ServerDir = "/www/wwwroot/psy/psy-front"
$TempDir = "${ServerDir}/dist.new"

# === 前端构建 ===
Write-Output "===== Begin Frontend build ====="
cd $ProjectPath

# 使用 Start-Process 可靠执行 npm
$npm = "npm"
$args = "run", "build:prod"
$proc = Start-Process $npm -ArgumentList $args -NoNewWindow -Wait -PassThru
if ($proc.ExitCode -ne 0) {
    Write-Error "Frontend build fail!"
    exit $proc.ExitCode
}

# === 上传到临时目录 ===
Write-Output "===== Uploading build to temporary folder on server ====="
scp -r -o StrictHostKeyChecking=no "$ProjectPath\$BuildDir" "${ServerUser}@${ServerIp}:$TempDir"
if ($LASTEXITCODE -ne 0) {
    Write-Error "SCP upload fail!"
    exit $LASTEXITCODE
}

# === 删除旧的 dist 文件夹 ===
Write-Output "===== Removing old dist folder on server ====="
ssh -o StrictHostKeyChecking=no "${ServerUser}@${ServerIp}" "rm -rf ${ServerDir}/dist"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Failed to remove old dist folder!"
    exit $LASTEXITCODE
}

# === 重命名临时文件夹为正式文件夹 ===
Write-Output "===== Renaming new dist folder ====="
ssh -o StrictHostKeyChecking=no "${ServerUser}@${ServerIp}" "mv ${TempDir} ${ServerDir}/dist"
if ($LASTEXITCODE -ne 0) {
    Write-Error "Remote rename fail!"
    exit $LASTEXITCODE
}

Write-Output "===== Frontend build and deployment finished ====="
